#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include "Common.h"
#include "GenerateX86Code.h"
#include "../../WritePEFile/WritePEFile/WritePEFile.h"

#ifdef _DEBUG
#pragma comment (lib, "../../WritePEFile/Debug/WritePEFile.lib")
#else
#pragma comment (lib, "../../WritePEFile/Release/WritePEFile.lib")
#endif

extern FILE *yyin;
int yyparse();

struct Instruction intermediateCodeData[INTERMEDIATE_CODE_DATA_SIZE] = {0};
struct Instruction* intermediateCode;

struct Identifier identifierData[JMP_LABEL_DATA_SIZE] = {0};
struct Identifier* identifiers;

int main(int argc, char** argv)
{
	FILE* exe = NULL;
	UInt8 code[INTERMEDIATE_CODE_DATA_SIZE] = {0};
	UInt codeSize;
	intermediateCode = intermediateCodeData;
	identifiers = identifierData;
	yyin = NULL;

#if 0
	if (argc != 1)
	{
		int i;
		for (i = 1; i <= argc; ++i)
		{
			if (GetFileAttributesA(argv[i]) != INVALID_FILE_ATTRIBUTES)
			{
				yyin = fopen(argv[i], "r");
				break;
			}
		}
	}
#endif
	exe = fopen("./out.exe", "w");
	if (!exe)
	{
		printf("ERROR: Unable to open EXE file\n");
		goto End;
	}

	yyin = fopen(".\\source.txt", "r");
	if (!yyin)
	{
		printf("ERROR: Unable to open source file\n");
		goto End;
	}

	// Parsing
	yyparse();

	// Reset pointer to intermediate code
	intermediateCode = intermediateCodeData;

	// Code Generation
	codeSize = GenerateX86Code(code);

	// Write the EXE file
	WritePEFile(exe, code, codeSize);


End:
	if (exe)
		fclose(exe);
	if (yyin)
		fclose(yyin);

	if (_getch() == 'y')
		system("C:/Software/OllyDbg/OLLYDBG.EXE C:/Dev/X86Assembler/X86Assembler/out.exe");

	return 0;
}